package Service;

import java.util.*;

public class ServiceThread implements Runnable {

	protected static String INPUTHINT;
	protected static String CMDERRORHINT;
	protected static String TAG;
	
	Scanner input = new Scanner(System.in);
	
	protected CmdParser cmdParser;
	
	private boolean ifStopThread = true;
	
	public ServiceThread() {
		
		INPUTHINT = "Please enter the operation and content Separated by space:";
		CMDERRORHINT = "Error Command.";
		TAG = "Service has been exited.";
		
		this.cmdParser = new CmdParser();
	}

	@Override
	public void run() {
		
		printHint();
		
		while (ifStopThread) {
			System.out.println(INPUTHINT);
			String inputContent = input.nextLine();
			
			Map<String, Object> parseResult = cmdParser.parseInputContent(inputContent);
			String header = (String) parseResult.get("header");
			List<String> content = (List<String>) parseResult.get("content");
			
			if (cmdParser.isTheInputCorrectCommand(inputContent))
				handleCommand(header, content);
			else
				System.out.println(CMDERRORHINT);
		}
		
		System.out.println(TAG);
	}

	public void printHint() {
		
	}
	
	private void handleCommand(String header, List<String> content) {
		if (cmdParser.isHeaderTheExitCommand(header)) 
			StopSelfThreadAndAwakeSleepingThread(this);
		else 
			handleBussinessCommand(header, content);
	}

	protected void handleBussinessCommand(String header, List<String> content) {
		
	}
	
	private void StopSelfThreadAndAwakeSleepingThread(ServiceThread serviceThread) {
		ifStopThread = false;
		synchronized(serviceThread) {
			serviceThread.notify();
		}
	}

}
